<?php

class Core_Backend_Component_Design_Controller_Page_Theme extends Dcmp_Component_Controller {
	
    public function indexAction($integer_pageindex = 1, $integer_pagesize = 20, $sort = 'id', $dir = 'desc') {
        $this->getHistory()->record();
        $validator = $this->getRequest()->getValidator('filter');
        $collection = App::getModel('design/collection_page_theme')
                        ->filterByAreaId($this->getSession()->get('managed_area_id'))
                        ->pagination($integer_pageindex, $integer_pagesize);
        if ($validator->isNotEmpty('name')) {
            $collection->filterByName($validator->getValue('name'));
        }
        $collection->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function createAction() {
        return $this->viewResult();
    }

    public function editAction($id) {
        $model = App::getModel('design/page_theme')->load($id);
        return $this->createAction()->setModel($model);
    }

    public function applyPostAction() {
        return $this->saveModel(FALSE);
    }

    public function savePostAction() {
        return $this->saveModel();
    }

    private function saveModel($return = TRUE) {
        $data = $this->getRequest()->getForm('theme');
        $model = App::getModel('design/page_theme');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data);
        $model->setAreaId($this->getSession()->get('managed_area_id'));
        if (($errors = $model->validate()) === TRUE) {
            $model->save();
            $area = App::getModel('global/area')->load($model->getAreaId());
            $websiteThemes = App::getModel('design/collection_website_theme')->load();
            foreach ($websiteThemes as $theme) {
                Kd_Util_IO::makeDirectory(DP_DESIGN . 
                                $area->getNamespace() . DS .
                                $theme->getName() . DS .
                                'template' . DS .
                                $model->getType() . DS .
                                $model->getName());
            }
            $this->getMessager()->addInform($this->__('share.message.success'));
            return $return ?
                    $this->redirectResult($this->getHistoryUrl('design/page_theme/index')) :
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit'));
        } else {
            $this->getMessager()
                    ->addError($this->__('share.message.fail'))
                    ->addError($errors);
            return $this->viewResult(array('model' => $model));
        }
    }

}